package io.yuncheng.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.exception.RRException;
import io.yuncheng.common.utils.SysDictConstant;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.SubApplicationService;
import io.yuncheng.modules.sys.dao.SubAppWarnLogDao;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.SubAppWarnLogService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.yuncheng.common.utils.PageUtils;
import io.yuncheng.common.utils.Query;

import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service("subAppWarnLogService")
public class SubAppWarnLogServiceImpl extends ServiceImpl<SubAppWarnLogDao, SubAppWarnLogEntity> implements SubAppWarnLogService {
    @Resource
    private SubApplicationService subApplicationService;
    @Resource
    private DictConfig dictConfig;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Object appType = params.get("appType");
        Object appTypes = params.get("appTypes");
        Object arithId = params.get("arithId");
        Object appId = params.get("appId");
        Object appUniqueId = params.get("appUniqueId");
        EntityQueryVo data =  (EntityQueryVo)params.get("data");
        if(data == null){
            data = new EntityQueryVo();
        }
        if(appTypes!=null){
            data.setTypeList(appTypes.toString().split(","));
        }
        IPage<SubAppWarnLogEntity> page = this.page(
                new Query<SubAppWarnLogEntity>().getPage(params),
                new QueryWrapper<SubAppWarnLogEntity>()
                        .eq(appType!=null,"app_type",appType)
                        .eq(appId!=null,"app_id",appId)
                        .eq(arithId!=null,"arith_id",arithId)
                        .eq(appUniqueId!=null,"app_unique_id",appUniqueId)
                        .in(!ObjectUtils.isEmpty(data.getStringList()),"app_unique_id",data.getStringList())
                        .in(!ObjectUtils.isEmpty(data.getTypeList()),"app_type",data.getTypeList())
                        .orderByDesc("log_date")
        );
        List<SubAppWarnLogEntity> records = page.getRecords();
        Map<String, SubApplicationEntityVo> collect = data.getSubApplicationEntities().stream().collect(Collectors.toMap(a -> a.getUniqueAppId(), a -> a, (k1, k2) -> k1));
        List<SubAppWarnLogVo> voList = records.stream().map(a ->{
            SubAppWarnLogVo subAppWarnLogVo = buildByEntity(a);
            if(collect.containsKey(a.getAppUniqueId())){
                subAppWarnLogVo.setAppName(collect.get(a.getAppUniqueId()).getAppName());
                subAppWarnLogVo.setParentDeptName(collect.get(a.getAppUniqueId()).getParentDeptName());
            }
            String sysDictValue = dictConfig.getSysDictValue(SysDictConstant.ARITH, subAppWarnLogVo.getArithId() + "");
            subAppWarnLogVo.setArithName(sysDictValue);
            return subAppWarnLogVo;
        } ).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(voList);
        return pageUtils;
    }
    @Override
    public PageUtils queryPageBuildParam(Map<String, Object> params) {
        Object deptId = params.get("deptId");
        Object logAppType = params.get("logAppType");
        if(deptId != null){
            SubApplicationEntity subApplicationEntity = subApplicationService.queryByDeptId(Long.valueOf(deptId.toString()));
            if(subApplicationEntity==null){
                throw new RRException("无该机构");
            }
            params.putIfAbsent("appUniqueId",subApplicationEntity.getUniqueAppId());
        }
        //增加权限过滤
        List<SubApplicationEntityVo> subApplicationEntities = subApplicationService.queryConfirmList(new HashMap<>(4));
        EntityQueryVo entityQueryVo = new EntityQueryVo();
        if(logAppType!=null){
            Integer logAppType1 = Integer.valueOf(logAppType.toString()) ;
            subApplicationEntities = subApplicationEntities.stream().filter(a -> a.getAppType().equals(logAppType1)).collect(Collectors.toList());
        }
        entityQueryVo.setSubApplicationEntities(subApplicationEntities);
        Object[] objects = subApplicationEntities.stream().map(a -> a.getUniqueAppId()).collect(Collectors.toList()).toArray();
        entityQueryVo.setStringList(objects);
        params.putIfAbsent("data",entityQueryVo);
        if(ObjectUtils.isEmpty(subApplicationEntities)){
            return  new PageUtils(new Page<>());
        }
        return queryPage(params);
    }

    @Override
    public void saveOrUpdateByTransactionId(SubAppWarnLogEntity entity) {
        QueryWrapper<SubAppWarnLogEntity> queryWrapper = new QueryWrapper<>();
        SubAppWarnLogEntity en = new SubAppWarnLogEntity();
        en.setTransactionId(entity.getTransactionId());
        en.setAppUniqueId(entity.getAppUniqueId());
        queryWrapper.setEntity(en);
        List<SubAppWarnLogEntity> list = list(queryWrapper);
        entity.setCreateDate(new Date());
        if(ObjectUtils.isEmpty(list)){
           save(entity);
           return;
        }
        SubAppWarnLogEntity subAppWarnLogEntity = list.get(0);
        entity.setId(subAppWarnLogEntity.getId());
        updateById(entity);
    }

    @Override
    public void saveWarnLogOuter(AgentWarningLogEntity warningLogEntity) {
        SubAppWarnLogEntity subAppWarnLogEntity = warningLogEntity.buildByLog();
        String sysDictValue = dictConfig.getSysDictValue(SysDictConstant.LOG_WARN_TYPE_ID, warningLogEntity.getAlarmtype());
        if(!ObjectUtils.isEmpty(sysDictValue)){
            subAppWarnLogEntity.setAppType(Integer.valueOf(sysDictValue));
        }
        subAppWarnLogEntity.setAppWarnCode(warningLogEntity.getAlarmtype());

        if( warningLogEntity.getAlgorithm()!=null){
            String alogorithm = warningLogEntity.getAlgorithm().toUpperCase();
            String alogId = dictConfig.getSysDictCode(SysDictConstant.ARITH, alogorithm);
            if(!ObjectUtils.isEmpty(alogId)){
                subAppWarnLogEntity.setArithId(Integer.valueOf(alogId));
            }
        }
        saveOrUpdateByTransactionId(subAppWarnLogEntity);
    }

    private SubAppWarnLogVo buildByEntity(SubAppWarnLogEntity entity){
        String s = JSON.toJSONString(entity);
        SubAppWarnLogVo subAppWarnLogVo = JSON.parseObject(s, SubAppWarnLogVo.class);
        String code;
        if(!ObjectUtils.isEmpty(entity.getAppType())){
            code = entity.getAppType().toString();
        }else {
            code = dictConfig.getSysDictValue(SysDictConstant.LOG_WARN_TYPE_ID, entity.getAppWarnCode());
        }
        String sysDictValue = dictConfig.getSysDictValue(SysDictConstant.LOG_WARN_ID, code);
        subAppWarnLogVo.setAppTypeName(sysDictValue);
        return subAppWarnLogVo;
    }

}
